package com.slashmanx.goals2u;

import java.util.ArrayList;

import org.json.JSONException;

import com.slashmanx.goals2u.others.MarqueeViewSingle;
import com.slashmanx.goals2u.others.Utilities;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Main extends Activity {
    /** Called when the activity is first created. */
    public static String type = "all";
    
    public LayoutInflater factory;

    public View mainListView;

    public static ArrayList<Match> MatchList = new ArrayList<Match>();
    private Intent intent;
    public GoalsDatabaseManager db;
	

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.menu);
        MarqueeViewSingle ticker = (MarqueeViewSingle) findViewById(R.id.tickerMarquee);
        ticker.setText1("Loading...");
        ticker.startMarquee();

        intent = new Intent(this, GoalsService.class);
        
        startService(intent);
        registerReceiver(broadcastReceiver, new IntentFilter(GoalsService.BROADCAST_ACTION));

        db = new GoalsDatabaseManager(this); 
        update(db, null);
        //db.clearDatabase();
        Match.setCounter(1);

    }
    
    public void openScores(View v)
    {
    	TableRow row = (TableRow)findViewById(v.getId());
    	Intent intent = new Intent(this, TabMain.class);
    	intent.putExtra("type", row.getTag().toString());
    	startActivity(intent);
    }
    
    public boolean onCreateOptionsMenu(Menu menu) { 
        menu.add(1,1,1,"Settings");
        menu.findItem(1).setIcon(android.R.drawable.ic_menu_manage);
        return super.onCreateOptionsMenu(menu);  
      } 
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
            	Intent pIntent = new Intent(this, Preferences.class);
            	startActivity(pIntent);
            	break;
        }
        return true;
    }
     
    
    
    
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	updateUI(intent);       
        }
    };    
    
	@Override
	public void onResume() {
		super.onResume();		
		startService(intent);
		if(db != null)
		{
            db.close();
		}
		db = new GoalsDatabaseManager(this);
		registerReceiver(broadcastReceiver, new IntentFilter(GoalsService.BROADCAST_ACTION));
	}
	
	@Override
	public void onPause() {
		super.onPause();		
		stopService(intent);
		if(db != null)
		{
			db.close();
		}
		db = null;
		try
		{
			//unregisterReceiver(broadcastReceiver);
		}
		catch(IllegalArgumentException iae)
		{
			// Ignore Exception
		}
	}
	
	public void onDestroy() {
		super.onDestroy();
		stopService(intent);
		if(db != null)
		{
			db.close();
		}
		db = null;
		try
		{
			unregisterReceiver(broadcastReceiver);
		}
		catch(IllegalArgumentException iae)
		{
			// Ignore Exception
		}
	}



    private void updateUI(Intent intent) {

    	update(db, null);
    }
    
    public static void setActiveType(String newType)
    {
        type = newType;
    }
    
    public void update(GoalsDatabaseManager db, ArrayAdapter<Match> adapter)
    {
    	if(db != null)
		{
    		db.close();
    		db = null;
		}
    	db = new GoalsDatabaseManager(this);
    	
    	String ns = Context.NOTIFICATION_SERVICE;
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    	MarqueeViewSingle ticker = (MarqueeViewSingle) findViewById(R.id.tickerMarquee);
    	int icon = R.drawable.football;
    	Notification notification = new Notification();
    	notification.icon = icon;
    	
    	
    	
    	try {
        	
        	String text = "";
        	
        	
        	ArrayList<Match> newMatchList = Utilities.getScores(db, "all", "all");
        	if(Main.MatchList != null)
        	{
        		
        		for(Match m : MatchList)
	        	{
	        		text += " "+ m.toString();
	        	}
	        	
	        	ticker.setText1(text);
        	}
        	if(newMatchList != null)
        	{
	        	SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext());
	        	boolean doNotify = sharedPrefs.getBoolean("notify", true);
	        	if(doNotify)
	        	{
		        	if(Main.MatchList != null)
		        	{
		        		
		        		for(Match m : MatchList)
			        	{
			        		text += " "+ m.toString();
			        	}
			        	
			        	ticker.setText1(text);
		        		
			        	for(int i = 0; i < MatchList.size(); i++)
			        	{
			        		Match tmp = newMatchList.get(i);
			        		if( (tmp.getHomeTeam().equals(Main.MatchList.get(i).getHomeTeam()) && 
			        				tmp.getAwayTeam().equals(Main.MatchList.get(i).getAwayTeam()) ) &&
			        				( (tmp.getHomeScore() != Main.MatchList.get(i).getHomeScore()) || 
			        					tmp.getAwayScore() != Main.MatchList.get(i).getAwayScore()) )
			        		{
			        			
			        			
			        			CharSequence notifText = "GOAL! "+ newMatchList.get(i).toString();
			        	    	long when = System.currentTimeMillis();
		
			        	    	notification.tickerText = notifText;
			        	    	notification.when = when;
			        	    	notification.defaults |= Notification.DEFAULT_VIBRATE;
			        	    	notification.flags |= Notification.FLAG_AUTO_CANCEL;
			        	    	
			        	    	Context context = getApplicationContext();
			        	    	CharSequence contentTitle = "GOAL!";
			        	    	CharSequence contentText = notifText;
			        	    	Intent notificationIntent = new Intent(this, MatchScreen.class);
			        	    	notificationIntent.putExtra("matchID", tmp.getId());
			        	    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		
			        	    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
			        	    	
			        	    	int MATCH_ID = tmp.getId();
		
			        	    	mNotificationManager.notify(MATCH_ID, notification);
			        		}
			        	}
		        	}
	        	}
	        	Main.MatchList = newMatchList;
	        	text = "";
	        	
	        	for(Match m : newMatchList)
	        	{
	        		text += " "+ m.toString();
	        	}
	        	
	        	ticker.setText1(text);
        	}
        	
        	else if(!Utilities.isOnline(this))
        	{
        		Toast.makeText(this.getBaseContext(), "Unable to get matches", Toast.LENGTH_LONG);
        		ticker.setText1("Couldn't connect to scores service. Make sure you are connected to the internet.");
        	}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

}